Sending Mails with SMTP
This lesson explains how Go code can be used to send an email using an SMTP server.
We'll cover the following
Overview of SMTP in Go#
The package net/smtp implements the Simple Mail Transfer Protocol for sending mail. It contains a Client type that represents a client connection to an SMTP server:
Dialreturns a newClientconnected to an SMTP server.- Set
Mail(=from) andRcpt(= to) Datareturns a writer that can be used to write the data, here withbuf.WriteTo(wc).
Explanation#
In the code above, we need the package net/smtp, which is imported at line 5. First, we need to connect to an active remote SMTP server, which is done with the Dial method at line 10, creating a client instance. Error-handling (from line 11 to line 13) exits the program on error.
We set up the sender and receiver email address at line 15 and line 16, respectively. Line 18 constructs the Data method on client, which makes a client writer wc with similar error-handling from line 19 to line 21. At line 22, we make sure that the writer wc will be closed. Then, at line 23, we make a buffered string and write it to wc at line 24. This if-statement is combined with error-handling, logging an eventual error and exiting the program at line 25.
The function SendMail can be used if authentication is needed and when you have a number of recipients. It connects to the server at addr, switches to TLS (Transport Layer Security encryption and authentication protocol), authenticates with the mechanism if possible, and then sends an email from address from to addresses to, with the message msg:
func SendMail(addr string, a Auth, from string, to []string, msg []byte) error
Go through the following illustrations that explain how to set a Gmail account for sending an email before running a program.
1 of 7
2 of 7
3 of 7
4 of 7
5 of 7
6 of 7
7 of 7
Look at the following program to see how it works:
/
Click the RUN button and wait for the terminal to start. Type go run main.go in the terminal and press ENTER.
Hurrah! You just sent your first email with Go! Cloud computing is so popular nowadays, and Go provides support for it. See the next lesson to see how Golang has made this possible.
Remote Procedure Calls with RPC
Go in the Cloud